package com.elepro.shoppingmall.service.user;

import com.elepro.shoppingmall.entity.Message;
import com.elepro.shoppingmall.entity.UserMessage;
import com.elepro.shoppingmall.mapper.MessageMapper;
import com.elepro.shoppingmall.mapper.UserMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {
    @Resource
    private MessageMapper messageMapper;
    @Resource
    private UserMapper userMapper;

    //发布消息
    @Override
    public int insertMessage(Message message) {
        try {
            messageMapper.insertMessage(message);
            return insertUserMessage(message.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    //向所有普通用户发布消息
    @Override
    public int insertUserMessage(long messageId) {
        //查询所有普通用户Id
        List<Long> userIdList = userMapper.getAllCommonUser();

        try {
            for (Long userId : userIdList) {
                UserMessage userMessage = new UserMessage();
                userMessage.setUserId(userId);
                userMessage.setMessageId(messageId);
                userMessage.setStatus(0);
                messageMapper.insertUserMessage(userMessage);
            }
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    //删除消息
    @Override
    public int deleteMessageById(long id) {
        try {
            messageMapper.deleteMessageById(id);
            return deleteUserMessageByMessageId(id);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    //向每个普通用户删除消息
    @Override
    public int deleteUserMessageByMessageId(long id) {
        try {
            return messageMapper.deleteUserMessageByMessageId(id);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    //查询所有消息
    @Override
    public List<Message> getAllMessage() {
        return messageMapper.getAllMessage();
    }

    //用户查询所有消息
    @Override
    public List<Message> getUserAllMessage(long userId) {
        return messageMapper.getUserAllMessage(userId);
    }
}
